package com.example.littleken.recyclerviewtext.Adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.littleken.recyclerviewtext.R;

/**RecyclerView的适配器，继承至RecyclerView.Adapter
 * Created by littleken on 2018/5/3.
 */
//RecyclerView.Adapter为泛型类
public class GridAdapter extends RecyclerView.Adapter<GridAdapter.LinearViewHolder> {
    private Context context;

    public GridAdapter(Context context) {
        this.context = context;
    }

    /**
     * 获取每个item的view
     * @param parent
     * @param viewType
     * @return view
     */
    @Override
    public GridAdapter.LinearViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //构造器需要传参：每个item的布局view
        //LayoutInflater.from(context).inflate(R.layout.layout_linear_item,parent,false)通过xml布局文件反射出对应的view
        return new LinearViewHolder(LayoutInflater.from(context).inflate(R.layout.layout_grid_item,parent,false));
    }

    /**
     * 绑定hodler
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(GridAdapter.LinearViewHolder holder, final int position) {
        holder.textView.setText("hello!");
        //设置点击监听
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context,"hahaha"+position,Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 获取列表长度
     * @return
     */
    @Override
    public int getItemCount() {
        return 10;
    }

    /**
     * viewHolder类，作用同于ListView中的viewHodler
     */
    class LinearViewHolder extends RecyclerView.ViewHolder{
        private TextView textView;

        public LinearViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView.findViewById(R.id.tv_title);

        }
    }
}
